import { get, post, put, del } from "./api";

export const companyService = {
  async getCompanies(params = { page: 1, pageSize: 10 }) {
    try {
      const response = await get("companies");
      const allCompanies = Array.isArray(response)
        ? response
        : response.content || [];

      const startIndex = (params.page - 1) * params.pageSize;
      const endIndex = startIndex + params.pageSize;
      const paginatedCompanies = allCompanies.slice(startIndex, endIndex);

      return {
        items: paginatedCompanies,
        total: allCompanies.length,
        totalPages: Math.ceil(allCompanies.length / params.pageSize),
        currentPage: params.page,
      };
    } catch (error) {
      throw new Error(error.message || "获取企业列表失败");
    }
  },

  async getAllCompanies() {
    try {
      const response = await get("companies");
      return Array.isArray(response) ? response : response.content || [];
    } catch (error) {
      throw new Error(error.message || "获取企业列表失败");
    }
  },

  async getCompany(id) {
    try {
      const companyId = parseInt(id);
      if (isNaN(companyId)) {
        throw new Error("无效的企业ID");
      }
      const response = await get(`companies/${companyId}`);
      return response;
    } catch (error) {
      if (error.response?.status === 404) {
        throw new Error("企业不存在");
      }
      throw new Error(error.message || "获取企业信息失败");
    }
  },

  async createCompany(companyData) {
    try {
      const response = await post("companies", companyData, true);
      return response;
    } catch (error) {
      throw new Error(error.message || "创建企业失败");
    }
  },

  async updateCompany(id, companyData) {
    try {
      const companyId = parseInt(id);
      if (isNaN(companyId)) {
        throw new Error("无效的企业ID");
      }
      const response = await put(`companies/${companyId}`, companyData, true);
      return response;
    } catch (error) {
      throw new Error(error.message || "更新企业失败");
    }
  },

  async deleteCompany(id) {
    try {
      const companyId = parseInt(id);
      if (isNaN(companyId)) {
        throw new Error("无效的企业ID");
      }
      const response = await del(`companies/${companyId}`);
      return response;
    } catch (error) {
      throw new Error(error.message || "删除企业失败");
    }
  },

  async batchDeleteCompanies(companyIds) {
    try {
      const deletePromises = companyIds.map((id) => this.deleteCompany(id));
      await Promise.all(deletePromises);
      return { success: true };
    } catch (error) {
      console.error("批量删除企业失败:", error);
      throw error;
    }
  },
};
